package cn.school.student.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.school.basics.dao.BaseSubjectDao;

import cn.school.basics.vo.BaseSubjectVO;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.FileUtil;
import cn.school.common.utils.SysUserUtils;
import cn.school.common.utils.XWPFUtils;
import cn.school.educational.entity.Subject;
import cn.school.educational.service.SubjectService;
import cn.school.student.dao.TExamPerformanceDao;
import cn.school.student.dao.TExamSubjectDao;

import cn.school.student.entity.TExamSubject;
import cn.school.student.entity.vo.TExamSubjectExcel;
import cn.school.student.entity.vo.UnitVo;
import cn.school.student.service.TExamSubjectService;
import cn.school.sys.entity.SysDictDetail;
import cn.school.sys.entity.SysUser;
import cn.school.sys.service.SysDictDetailService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.SyncReadListener;

import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.PageRequest;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * (TExamSubject)表服务实现类
 *
 * @author makejava
 * @since 2023-02-16 17:40:03
 */
@Service("tExamSubjectService")
public class TExamSubjectServiceImpl extends ServiceImpl<TExamSubjectDao, TExamSubject> implements TExamSubjectService {
    @Resource
    private TExamSubjectDao tExamSubjectDao;

    @Autowired
    private TExamPerformanceDao tExamPerformanceDao;
    @Autowired
    private SubjectService subjectService;

    @Autowired
    private BaseSubjectDao baseSubjectDao;

    @Autowired
    private SysDictDetailService sysDictDetailService;
    @Value("${school.imagePathStartDir}")
    private String filePath;

    @Value("${school.host}")
    private String host;



    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public TExamSubject queryById(Integer id) {
        return this.tExamSubjectDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param tExamSubject 筛选条件
     * @param pageRequest  分页对象
     * @return 查询结果
     */
    @Override
    public IPage<TExamSubject> queryByPage(TExamSubject tExamSubject, PageRequest pageRequest) {

        SysUser sysUser = SysUserUtils.getSysUser();
        tExamSubject.setCreateBy(sysUser.getUsername());
        List<TExamSubject> examInfoList = tExamSubjectDao.queryAllByLimit(tExamSubject, pageRequest);
        IPage<TExamSubject> page = new Page<>();
        page.setTotal(this.tExamSubjectDao.count(tExamSubject));
        page.setRecords(examInfoList);
        return page;
    }

    /**
     * 新增数据
     *
     * @param tExamSubject 实例对象
     * @return 实例对象
     */
    @Override
    public Integer insert(TExamSubject tExamSubject) {
        int insert = this.tExamSubjectDao.insert(tExamSubject);
        return insert;
    }

    /**
     * 修改数据
     *
     * @param tExamSubject 实例对象
     * @return 实例对象
     */
    @Override
    public Integer update(TExamSubject tExamSubject) {
        tExamSubject.setInvisible(tExamSubject.getInvisible().toString());
        return this.tExamSubjectDao.update(tExamSubject);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {

        int count = tExamPerformanceDao.queryPaperQuestion(Long.valueOf(id));

        if (count>0) {
            throw new ApiException("题目以被试卷使用不能删除！");
        }

        return this.tExamSubjectDao.deleteById(id) > 0;
    }

    @Override
    public CommonResult<Integer> tExamSubjectExcel(MultipartFile multipartFile) {


        List<Subject> list = subjectService.list();

        List<BaseSubjectVO> baseSubjectVOS = baseSubjectDao.selectList(null);
        List<SysDictDetail> dictList = sysDictDetailService.selectDictDataByType("class_grade");
        List<TExamSubject> subjectList = new ArrayList<>();
        try {

            List<TExamSubjectExcel> cs = EasyExcel.read(multipartFile.getInputStream())
                    .registerReadListener(new SyncReadListener())
                    .head(TExamSubjectExcel.class)
                    .sheet(0)
                    .headRowNumber(2)
                    .doReadSync();
            for(TExamSubjectExcel tExamSubject:cs){
                if (StringUtils.isEmpty(tExamSubject.getUnit())) {
                    throw new ExcelAnalysisException("答案不能为空");
                }
                if (tExamSubject.getQuestionsType().equals("单选题")) {
                    if (StringUtils.isEmpty(tExamSubject.getOptionA()) || StringUtils.isEmpty(tExamSubject.getOptionB())
                            || StringUtils.isEmpty(tExamSubject.getOptionC()) || StringUtils.isEmpty(tExamSubject.getOptionD())) {
                        throw new ExcelAnalysisException("单选题请填写ABCD四个选项");
                    }
                    List<UnitVo> UnitVoList = getUnitVos(tExamSubject);
                    tExamSubject.setOptions(JSON.toJSONString(UnitVoList));
                    tExamSubject.setQuestionsType("1");
                }
                if (tExamSubject.getQuestionsType().equals("多选题")) {
                    if (StringUtils.isEmpty(tExamSubject.getOptionA()) || StringUtils.isEmpty(tExamSubject.getOptionB())
                            || StringUtils.isEmpty(tExamSubject.getOptionC()) || StringUtils.isEmpty(tExamSubject.getOptionD())) {
                        throw new ExcelAnalysisException("多选题请填写ABCD四个选项");
                    }
                    String[] split = tExamSubject.getUnit().split(",");
                    List<UnitVo> unitVoList = new ArrayList<>();
                    for (int i = 0; i < 4; i++) {
                        UnitVo unitVo = new UnitVo();
                        String optIdx = switchVal(i + 1);
                        unitVo.setOptIdx(optIdx);
                        unitVo.setIsRight(false);
                        for (String s : split) {
                            if (optIdx.equals(s)) {
                                unitVo.setOptIdx(optIdx);
                                unitVo.setIsRight(true);
                            }
                        }
                        unitVoList.add(unitVo);
                    }
                    if (unitVoList.size() > 0) {
                        tExamSubject.setUnit(JSON.toJSONString(unitVoList));
                    }
                    List<UnitVo> UnitVoList = getUnitVos(tExamSubject);
                    tExamSubject.setOptions(JSON.toJSONString(UnitVoList));
                    tExamSubject.setQuestionsType("2");
                }
                if (tExamSubject.getQuestionsType().equals("判断题")) {
                    tExamSubject.setQuestionsType("3");
                    if (tExamSubject.getUnit().equals("对")) {
                        tExamSubject.setUnit("yes");
                    }
                    if (tExamSubject.getUnit().equals("错")) {
                        tExamSubject.setUnit("wrong");
                    }
                }
                if (tExamSubject.getQuestionsType().equals("填空题")) {
                    tExamSubject.setQuestionsType("4");
                    String[] split = tExamSubject.getUnit().split(",");
                    List<UnitVo> listunis = new ArrayList<>();
                    for (int i = 0; i < split.length; i++) {
                        UnitVo unitVo = new UnitVo();
                        unitVo.setOptIdx(String.valueOf(i + 1));
                        unitVo.setIsRight(true);
                        unitVo.setOptTxt(split[i]);
                        listunis.add(unitVo);
                    }
                    tExamSubject.setUnit(JSON.toJSONString(list));
                }
                if (tExamSubject.getQuestionsType().equals("问答题")) {
                    tExamSubject.setQuestionsType("5");
                }
                if(tExamSubject.getUnit().length()>2000){
                    throw new ExcelAnalysisException("答案内容过长");
                }
                Subject next = list.stream().filter(subject -> tExamSubject.getSubjects().equals(subject.getSubjName())).iterator().next();
                tExamSubject.setSubjects(String.valueOf(next.getId()));
                BaseSubjectVO next1 = baseSubjectVOS.stream().filter(baseSubjectVO -> baseSubjectVO.getSubjectName().equals(tExamSubject.getMajor())).iterator().next();
                tExamSubject.setMajor(String.valueOf(next1.getId()));
                SysDictDetail sysdict = dictList.stream().filter(sysdictDetail -> sysdictDetail.getDictLabel().equals(tExamSubject.getGrade())).iterator().next();
                TExamSubject tExamSubject1 = BeanUtil.toBean(tExamSubject, TExamSubject.class);
                tExamSubject1.setCreateTime(new Date());
                tExamSubject1.setGrade(sysdict.getDictValue());
                tExamSubject1.setCreateBy(SysUserUtils.getSysUser().getUsername());
                subjectList.add(tExamSubject1);

            }
//            EasyExcel.read(multipartFile.getInputStream(), TExamSubjectExcel.class, new SyncReadListener() {
//                @Override
//                public void invoke(Object object, AnalysisContext context) {
//
//                    //读取到的数据被存入bean
//                    TExamSubjectExcel tExamSubject = (TExamSubjectExcel) object;
//
//                    if (StringUtils.isEmpty(tExamSubject.getUnit())) {
//                        throw new ExcelAnalysisException("答案不能为空");
//                    }
//                    if (tExamSubject.getQuestionsType().equals("单选题")) {
//                        if (StringUtils.isEmpty(tExamSubject.getOptionA()) || StringUtils.isEmpty(tExamSubject.getOptionB())
//                                || StringUtils.isEmpty(tExamSubject.getOptionC()) || StringUtils.isEmpty(tExamSubject.getOptionD())) {
//                            throw new ExcelAnalysisException("单选题请填写ABCD四个选项");
//                        }
//
//                        List<UnitVo> UnitVoList = getUnitVos(tExamSubject);
//                        tExamSubject.setOptions(JSON.toJSONString(UnitVoList));
//                        tExamSubject.setQuestionsType("1");
//
//
//                    }
//                    if (tExamSubject.getQuestionsType().equals("多选题")) {
//                        if (StringUtils.isEmpty(tExamSubject.getOptionA()) || StringUtils.isEmpty(tExamSubject.getOptionB())
//                                || StringUtils.isEmpty(tExamSubject.getOptionC()) || StringUtils.isEmpty(tExamSubject.getOptionD())) {
//                            throw new ExcelAnalysisException("多选题请填写ABCD四个选项");
//                        }
//                        String[] split = tExamSubject.getUnit().split(",");
//                        List<UnitVo> unitVoList = new ArrayList<>();
//                        for (int i = 0; i < 4; i++) {
//                            UnitVo unitVo = new UnitVo();
//                            String optIdx = switchVal(i + 1);
//                            unitVo.setOptIdx(optIdx);
//                            unitVo.setIsRight(false);
//                            for (String s : split) {
//                                if (optIdx.equals(s)) {
//                                    unitVo.setOptIdx(optIdx);
//                                    unitVo.setIsRight(true);
//                                }
//                            }
//                            unitVoList.add(unitVo);
//                        }
//                        if (unitVoList.size() > 0) {
//                            tExamSubject.setUnit(JSON.toJSONString(unitVoList));
//                        }
//                        List<UnitVo> UnitVoList = getUnitVos(tExamSubject);
//                        tExamSubject.setOptions(JSON.toJSONString(UnitVoList));
//                        tExamSubject.setQuestionsType("2");
//                    }
//                    if (tExamSubject.getQuestionsType().equals("判断题")) {
//                        tExamSubject.setQuestionsType("3");
//                        if (tExamSubject.getUnit().equals("对")) {
//                            tExamSubject.setUnit("yes");
//                        }
//                        if (tExamSubject.getUnit().equals("错")) {
//                            tExamSubject.setUnit("wrong");
//                        }
//                    }
//                    if (tExamSubject.getQuestionsType().equals("填空题")) {
//                        tExamSubject.setQuestionsType("4");
//                        String[] split = tExamSubject.getUnit().split(",");
//                        List<UnitVo> list = new ArrayList<>();
//                        for (int i = 0; i < split.length; i++) {
//                            UnitVo unitVo = new UnitVo();
//                            unitVo.setOptIdx(String.valueOf(i + 1));
//                            unitVo.setIsRight(true);
//                            unitVo.setOptTxt(split[i]);
//                            list.add(unitVo);
//                        }
//                        tExamSubject.setUnit(JSON.toJSONString(list));
//                    }
//                    if (tExamSubject.getQuestionsType().equals("问答题")) {
//                        tExamSubject.setQuestionsType("5");
//                    }
//                    if(tExamSubject.getUnit().length()>2000){
//                        throw new ExcelAnalysisException("答案内容过长");
//                    }
//                    Subject next = list.stream().filter(subject -> tExamSubject.getSubjects().equals(subject.getSubjName())).iterator().next();
//                    tExamSubject.setSubjects(String.valueOf(next.getId()));
//
//                    BaseSubjectVO next1 = baseSubjectVOS.stream().filter(baseSubjectVO -> baseSubjectVO.getSubjectName().equals(tExamSubject.getMajor())).iterator().next();
//                    tExamSubject.setMajor(String.valueOf(next1.getId()));
//
//                    SysDictDetail sysdict = dictList.stream().filter(sysdictDetail -> sysdictDetail.getDictLabel().equals(tExamSubject.getGrade())).iterator().next();
//
//                    TExamSubject tExamSubject1 = BeanUtil.toBean(tExamSubject, TExamSubject.class);
//                    tExamSubject1.setCreateTime(new Date());
//                    tExamSubject1.setGrade(sysdict.getDictValue());
//                    tExamSubject1.setCreateBy(SysUserUtils.getSysUser().getUsername());
//                    subjectList.add(tExamSubject1);
////                    insert[0] = tExamSubjectDao.insert(tExamSubject1);
//                }
//
//                @NotNull
//                private List<UnitVo> getUnitVos(TExamSubjectExcel tExamSubject) {
//                    List<UnitVo> UnitVoList = new ArrayList<>();
//                    UnitVo voA = new UnitVo();
//                    voA.setOptIdx("A");
//                    voA.setOptTxt(tExamSubject.getOptionA());
//                    UnitVoList.add(voA);
//                    UnitVo voB = new UnitVo();
//                    voB.setOptIdx("B");
//                    voB.setOptTxt(tExamSubject.getOptionB());
//                    UnitVoList.add(voB);
//                    UnitVo voC = new UnitVo();
//                    voC.setOptIdx("C");
//                    voC.setOptTxt(tExamSubject.getOptionC());
//                    UnitVoList.add(voC);
//                    UnitVo voD = new UnitVo();
//                    voD.setOptIdx("D");
//                    voD.setOptTxt(tExamSubject.getOptionD());
//                    UnitVoList.add(voD);
//                    return UnitVoList;
//                }
//
//            }).headRowNumber(2).doReadAll();

        } catch (ExcelAnalysisException | IOException e) {
            return CommonResult.failed(e.getMessage());
        }

        //检查必填内容
        for (TExamSubject tExamSubject1 : subjectList) {
            tExamSubject1.setInvisible("1");
            tExamSubjectDao.insert(tExamSubject1);
        }

        return CommonResult.success();

    }

    /**
     *
     * @param tExamSubject
     * @return
     */
    private List<UnitVo> getUnitVos(TExamSubjectExcel tExamSubject) {
        List<UnitVo> UnitVoList = new ArrayList<>();
        UnitVo voA = new UnitVo();
        voA.setOptIdx("A");
        voA.setOptTxt(tExamSubject.getOptionA());
        UnitVoList.add(voA);
        UnitVo voB = new UnitVo();
        voB.setOptIdx("B");
        voB.setOptTxt(tExamSubject.getOptionB());
        UnitVoList.add(voB);
        UnitVo voC = new UnitVo();
        voC.setOptIdx("C");
        voC.setOptTxt(tExamSubject.getOptionC());
        UnitVoList.add(voC);
        UnitVo voD = new UnitVo();
        voD.setOptIdx("D");
        voD.setOptTxt(tExamSubject.getOptionD());
        UnitVoList.add(voD);
        return UnitVoList;
    }

    public List<TExamSubject> readDocFileData(InputStream is,String grade,String major,String subjectId) throws IOException {
        XWPFDocument doc = new XWPFDocument(is);
        List<XWPFParagraph> paragraphs = doc.getParagraphs();
        TExamSubject examSubject = null;
        String questionsName = "";
        //当前题型
        String questionsType="";
        Map<String,String> map = null;
        List<Map<String,String>> qList = new ArrayList<>();
        List<TExamSubject> allList = new ArrayList<>();
        for (int i = 0; i < paragraphs.size(); i++) {
            map = new HashMap<>();
            //顶部提示不读取
            if(i<5){
                continue;
            }
            //读取word每一行的文本
            String rowTxt = paragraphs.get(i).getParagraphText();
            //检查题目类型
            String type = getQuestionsType(rowTxt);
            if(!StringUtils.isEmpty(type)){
                questionsType = type;
            }
            //检查是否问标题
            String title = getTitle(paragraphs.get(i).getParagraphText());
            if(!StringUtils.isEmpty(title)){
                questionsName = subtractionTitleAnswer(title);
                if(examSubject!=null && !StringUtils.isEmpty(examSubject.getQuestionsName())){
                    //添加解析
                    addAnalysis(paragraphs,examSubject,i);
                    examSubject.setOptions(JSON.toJSONString(qList));
                    allList.add(examSubject);
                    //添加完后重置选项集合
                    qList = new ArrayList<>();
                }
                examSubject = new TExamSubject();

            }
            if("1".equals(questionsType) || "2".equals(questionsType)){//选择题
                if(StringUtils.isEmpty(title)){
                    //试题题目
                    if(rowTxt.indexOf("．")>0){
                        map.put("optIdx",rowTxt.substring(0,rowTxt.indexOf("．")));
                        map.put("optTxt",rowTxt.substring(rowTxt.indexOf("．")+1));
                    }
                    if(rowTxt.indexOf(".")>0){
                        map.put("optIdx",rowTxt.substring(0,rowTxt.indexOf(".")));
                        map.put("optTxt",rowTxt.substring(rowTxt.indexOf(".")+1));
                    }
                    //添加图片
                    addImageFIle(doc, paragraphs, map, i);
                    if(map.size()>0)
                    qList.add(map);
                }else{
                    //试题答案
                    String unit = getAnswer(title,questionsType);
                    examSubject.setUnit(unit);
                    examSubject.setQuestionsName(questionsName);
                    examSubject.setScoresScore(BigDecimal.ONE);
                    examSubject.setQuestionsType(questionsType);
                    examSubject.setGrade(grade);
                    examSubject.setSubjects(subjectId);
                    examSubject.setMajor(major);
                }
            }
            if("3".equals(questionsType)){
                if(!StringUtils.isEmpty(title)){
                    //添加判断题
                    String unit = getAnswer(title,questionsType);
                    examSubject.setUnit(unit);
                    String reg2 = "(?<=\\()[\\s\\S]*(?=\\))";
                    Pattern p2 = Pattern.compile(reg2);
                    Matcher m2 = p2.matcher(title);
                    String result = null;
                    if(m2.find()){
                        result = m2.group().trim();
                    }
                    examSubject.setQuestionsName(title.replaceAll(result,""));
                    examSubject.setScoresScore(BigDecimal.ONE);
                    examSubject.setQuestionsType(questionsType);
                    examSubject.setGrade(grade);
                    examSubject.setSubjects(subjectId);
                    examSubject.setMajor(major);
                }
            }
            if("4".equals(questionsType)){
                if(!StringUtils.isEmpty(title)){
                    String unit = getAnswer(title,questionsType);
                    examSubject.setQuestionsName(subtractionTitleAnswer(title));
                    examSubject.setUnit(unit);
                    examSubject.setScoresScore(BigDecimal.ONE);
                    examSubject.setOptions("");
                    examSubject.setQuestionsType(questionsType);
                    examSubject.setGrade(grade);
                    examSubject.setSubjects(subjectId);
                    examSubject.setMajor(major);
                }
            }
            if("5".equals(questionsType)){
                if(!StringUtils.isEmpty(title)){
                    examSubject.setQuestionsName(title);
                    examSubject.setUnit("");
                    examSubject.setScoresScore(BigDecimal.TEN);
                    examSubject.setOptions("");
                    addAnalysis(paragraphs,examSubject,i);
                    examSubject.setQuestionsType(questionsType);
                    examSubject.setGrade(grade);
                    examSubject.setSubjects(subjectId);
                    examSubject.setMajor(major);

                }else{
                    //添加解析
                    if(rowTxt.indexOf("五、")==-1){
                        examSubject.setAnalysis(rowTxt);
                    }

                }
            }

        }
        if(examSubject!=null && !StringUtils.isEmpty(examSubject.getQuestionsName())){
            examSubject.setOptions(JSON.toJSONString(qList));
            allList.add(examSubject);
        }
        for (TExamSubject tExamSubject : allList) {
            System.out.println(JSON.toJSONString(tExamSubject));
        }
        return allList;
    }


    public String read(InputStream is) throws Exception {
        String questionsName = "";
        XWPFDocument doc = new XWPFDocument(is);
        List<XWPFParagraph> paragraphs = doc.getParagraphs();
        //每一题的集合
        List<Map<String,String>> qList =new ArrayList<>();
        //当前题型
        String questionsType="";

        Map<String,String> map = null;
        TExamSubject examSubject = new TExamSubject();
        List<TExamSubject> docList = new ArrayList<>();
        for (int i = 0; i < paragraphs.size(); i++) {
            map = new HashMap<>();
            //读取word每一行的文本
            String rowTxt = paragraphs.get(i).getParagraphText();

            if(StringUtils.isEmpty(rowTxt)){
                continue;
            }
            String title = getTitle(paragraphs.get(i).getParagraphText());
            //检查题型
            String type = getQuestionsType(rowTxt);
            if(!StringUtils.isEmpty(type)){
                questionsType = type;
            }

            if("1".equals(questionsType) || "2".equals(questionsType)){//单选题or多选题
                if(!StringUtils.isEmpty(title) && !StringUtils.isEmpty(questionsType)){

                    //试题答案
                    String unit = getAnswer(title,questionsType);
                    examSubject.setUnit(unit);
                    examSubject.setQuestionsName(questionsName);
                    examSubject.setSore(BigDecimal.ONE);
                    examSubject.setOptions(JSON.toJSONString(qList));
                    //添加解析
                    addAnalysis(paragraphs,examSubject,i);
                    System.out.println(JSON.toJSONString(examSubject));

                    questionsName = subtractionTitleAnswer(title);


                    if(qList.size()>0){
                        docList.add(examSubject);
                        examSubject = new TExamSubject();
                        qList = new ArrayList<>();
                    }
                    //添加试题
//                  this.tExamSubjectDao.insert(examSubject);


                }else{
                    //试题题目
                    if(rowTxt.indexOf("．")>0){
                        map.put("optIdx",rowTxt.substring(0,rowTxt.indexOf("．")));
                        map.put("optTxt",rowTxt.substring(rowTxt.indexOf("．")+1));
                    }
                }


                //添加图片
                addImageFIle(doc, paragraphs, map, i);
                //添加一行选项数据
                if(map!=null && map.size()>0)
                qList.add(map);

            }
            System.out.println("读取文本：" + rowTxt);
            if("3".equals(questionsType)){
                if(qList.size()>0){
                    examSubject.setOptions(JSON.toJSONString(qList));
//                    addAnalysis(rowTxt,examSubject);
                    System.out.println(JSON.toJSONString(examSubject));
                    examSubject = new TExamSubject();
                    //添加完后清空选项集合
                    qList = new ArrayList<>();
                }
                if(!StringUtils.isEmpty(title)){
                    //添加判断题
                    String unit = getAnswer(title,questionsType);
                    examSubject.setUnit(unit);
                    String reg2 = "(?<=\\()[\\s\\S]*(?=\\))";
                    Pattern p2 = Pattern.compile(reg2);
                    Matcher m2 = p2.matcher(title);
                    String result = null;
                    if(m2.find()){
                        result = m2.group().trim();
                    }
                    examSubject.setQuestionsName(title.replaceAll(result,""));
                }

                examSubject.setSore(BigDecimal.ONE);
                examSubject.setOptions("");

//                addAnalysis(rowTxt,examSubject);
                System.out.println(JSON.toJSONString(examSubject));
                examSubject = new TExamSubject();

            }

            if("4".equals(questionsType)){
                if(!StringUtils.isEmpty(title)){
                    String unit = getAnswer(title,questionsType);
                    examSubject.setQuestionsName(title);
                    examSubject.setUnit(unit);
                    examSubject.setSore(BigDecimal.ONE);
                    examSubject.setOptions("");
//                    addAnalysis(rowTxt,examSubject);
                    System.out.println(JSON.toJSONString(examSubject));
                    examSubject = new TExamSubject();
                }
            }
            if("5".equals(questionsType)){
                if(!StringUtils.isEmpty(title)){
                    examSubject.setQuestionsName(title);
                    examSubject.setUnit("");
                    examSubject.setSore(BigDecimal.TEN);
                    examSubject.setOptions("");
                    addAnalysis(paragraphs,examSubject,i);
                    System.out.println(JSON.toJSONString(examSubject));
                    examSubject = new TExamSubject();
                }
            }


        }

        if(qList.size()>0){
            examSubject.setOptions(JSON.toJSONString(qList));
//            addAnalysis(rowTxt,examSubject);
            System.out.println(JSON.toJSONString(examSubject));
            examSubject = new TExamSubject();
            //添加完后清空选项集合
            qList = new ArrayList<>();
        }

//        for (Map<String, String> stringStringMap : qList) {
//            System.out.println(stringStringMap+"");
//        }


        XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
        List<XWPFPictureData> allPictures = doc.getAllPictures();
        for (XWPFPictureData allPicture : allPictures) {

            System.out.println(allPicture.getFileName());
        }
//        text = extractor.getText();
        return "";
    }

    /**
     * 添加解析
     * @param
     * @param examSubject
     */
    private void addAnalysis(List<XWPFParagraph> paragraphs, TExamSubject examSubject,Integer i){
        if(paragraphs.get(i-1).getParagraphText().indexOf("、")>=0){//标识换了题型标识
            if(paragraphs.get(i-2).getParagraphText().indexOf("解析")>=0 && !StringUtils.isEmpty(examSubject.getQuestionsName())){
                examSubject.setAnalysis(paragraphs.get(i-2).getParagraphText());
            }
        }else{
            if(paragraphs.get(i-1).getParagraphText().indexOf("解析")>=0 && !StringUtils.isEmpty(examSubject.getQuestionsName())){
                examSubject.setAnalysis(paragraphs.get(i-2).getParagraphText());
            }
        }

    }
    /**
     * 添加图片
     * @param doc
     * @param paragraphs
     * @param map
     * @param i
     * @throws IOException
     */
    private void addImageFIle(XWPFDocument doc, List<XWPFParagraph> paragraphs, Map<String, String> map, int i) throws IOException {
//        System.out.println(paragraphs.get(i).getParagraphText());
        List<String> imageBundleList = XWPFUtils.readImageInParagraph(paragraphs.get(i));
        if(!CollectionUtils.isEmpty(imageBundleList)){//有图片选项
            for (String s : imageBundleList) {
                XWPFPictureData pictureDataByID = doc.getPictureDataByID(s);
                InputStream input = new ByteArrayInputStream(pictureDataByID.getData());
                String fileDistPath = FileUtil.uploadFile(input,filePath,pictureDataByID.getFileName());
//                System.out.println(s+"  " + pictureDataByID.getFileName() + "  " + paragraphs.get(i).getParagraphText() + " " + fileDistPath);
                map.put("optTxt","<p><img src='"+host+fileDistPath+"'/></p>");
            }
        }
    }

    private String getQuestionsType(String text){
        String flag = null;
        if(!StringUtils.isEmpty(text) && text.startsWith("一、")){
            flag = "1";
        }
        if(!StringUtils.isEmpty(text) && text.startsWith("二、")){
            flag = "2";
        }
        if(!StringUtils.isEmpty(text) && text.startsWith("三、")){
            flag = "3";
        }
        if(!StringUtils.isEmpty(text) && text.startsWith("四、")){
            flag = "4";
        }
        if(!StringUtils.isEmpty(text) && text.startsWith("五、")){
            flag = "5";
        }
        return flag;
    }

    /**
     * 获取题目内容
     * @param str
     * @return
     */
    private String getTitle(String str){
        //判断是否是数字开头,数字开头的内容问题目标题
        Pattern pattern = Pattern.compile("^(\\d+)(.*)");
        Matcher matcher = pattern.matcher(str);


        if (matcher.matches()) {
            return str.substring(str.indexOf("．")+1);
        }
        return null;
    }

    /**
     * 去掉题目答案
     * @param title
     * @return
     */
    private String subtractionTitleAnswer(String title){
        String reg3 = "(?<=（)[\\s\\S]*(?=）)";
        Pattern p3 = Pattern.compile(reg3);
        Matcher m3 = p3.matcher(title);

        String reg4 = "(?<=__)[\\s\\S]*(?=__)";
        Pattern p4 = Pattern.compile(reg4);
        Matcher m4 = p4.matcher(title);

        String reg5 = "(?<=（)[\\s\\S]*(?=）)";
        Pattern p5 = Pattern.compile(reg5);
        Matcher m5 = p5.matcher(title);

        String tiankongReg1 = "(?<=\\()[^)]+(?=\\))";
        Pattern tiankongP1 = Pattern.compile(tiankongReg1);
        Matcher tiankongM1 = tiankongP1.matcher(title);

        String result="";
        String respStr="";
        while (m3.find()){
            result = m3.group().trim();
            title = title.replaceAll(result,respStr);
        }
        while(m4.find()){
            result = m4.group().trim();
            title = title.replaceAll(result,respStr);
        }
        while(m5.find()){
            respStr="  ";
            result = m5.group().trim();
            title = title.replaceAll(result,respStr);
        }
        while (tiankongM1.find()){
            respStr="  ";
            result = tiankongM1.group().trim();
            title = title.replaceAll(result,respStr);
        }
        return title;

    }
    /**
     * 获取答案
     * @param title
     * @return
     */
    private String getAnswer(String title,String type){
        String reg2 = "(?<=\\()[\\s\\S]*(?=\\))";
        String reg3 = "(?<=（)[\\s\\S]*(?=）)";
        String reg4 = "(?<=__)[\\s\\S]*(?=__)";

        Pattern p4 = Pattern.compile(reg4);
        Matcher m4 = p4.matcher(title);

        Pattern p3 = Pattern.compile(reg3);
        Matcher m3 = p3.matcher(title);

        Pattern p2 = Pattern.compile(reg2);
        Matcher m2 = p2.matcher(title);
        String result = null;
        if(m2.find()){
            result = m2.group().trim();
        }
        if(m3.find()){
            result = m3.group().trim();
        }
        if(m4.find()){
            result = m4.group().trim();
        }
        if(type.equals("2")){
            char[] chars = result.toCharArray();
            List<Map<String,Object>> unitList = new ArrayList<>();
            Map<String,Object> map = null;
            for (char aChar : chars) {
                map = new HashMap<>();
                map.put("isRight",true);
                map.put("optIdx",aChar);
                unitList.add(map);
            }
            return JSON.toJSONString(unitList);
        }else if(type.equals("3")){
            if (result.equals("√")){
                title = title.replaceAll(result,"");
                return "yes";
            }
            if (result.equals("×")){
                title = title.replaceAll(result,"");
                return "wrong";
            }
        }else if(type.equals("4")){
            //获取每个括号中间的内容
            List<Map<String, String>> list = setMoveTiankong(title);
            return JSON.toJSONString(list);
        }

        return result;

    }

    /**
     * 获取填空题中多个答案内容
     * @param title
     * @return
     */
    private List<Map<String, String>> setMoveTiankong(String title) {
        List<Map<String,String>> list= new ArrayList<>();
        Map<String,String> map=null;
        int num=1;

        String tiankongReg1 = "(?<=\\()[^)]+(?=\\))";
        Pattern tiankongP1 = Pattern.compile(tiankongReg1);
        Matcher tiankongM1 = tiankongP1.matcher(title);


        if(title.indexOf("__")>=0){
            map = new HashMap<>();
            String tiankongReg2 = "(?<=\\__)[^__]+(?=\\__)";
            Pattern tiankongP2 = Pattern.compile(tiankongReg2);
            Matcher tiankongM2 = tiankongP2.matcher(title);
            if(tiankongM2.find()){
                map.put("optIdx",num+"");
                map.put("optTxt",tiankongM2.group());
                list.add(map);
            }
        }
//            [{"optIdx":"1","optTxt":"1"}]

        while (tiankongM1.find()){
            map = new HashMap<>();
            map.put("optIdx",num+"");
            map.put("optTxt",tiankongM1.group());
            list.add(map);
            num++;
        }

        return list;
    }


    @Override
    public List<TExamSubject> tExamSubjectWord(MultipartFile file,String grade,String major,String subjectId) throws Exception {
        List<BaseSubjectVO> baseSubjectVOS = baseSubjectDao.selectList(null);
        List<SysDictDetail> dictList = sysDictDetailService.selectDictDataByType("class_grade");
        InputStream is = new BufferedInputStream(file.getInputStream());
        List<TExamSubject> read = readDocFileData(is,grade,major,subjectId);
        return read;
    }

    public static void main(String[] args) throws Exception {
        String text3 = "每隔定时器控件的Interval属性值时间间隔，单位为毫秒，定时器会触发一次__timer___事件";
        String reg3 = "(?<=\\__)[^__]+(?=\\__)";
        Pattern p3 = Pattern.compile(reg3);
        Matcher m3 = p3.matcher(text3);
        while (m3.find()){
            System.out.println(m3.group());
        }
    }

    @Nullable
    @Contract(pure = true)
    private String switchVal(int i) {
        switch (i) {
            case 1:
                return "A";
            case 2:
                return "B";
            case 3:
                return "C";
            case 4:
                return "D";
        }
        return null;
    }
}
